using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using IFWiki.Models;

namespace IFWiki.Controllers
{
    public class GamePlaceController : Controller
    {
        //
        // GET: /Game/

        public ActionResult Go(string placeName, string gameName)
        {
            var gamePlace = new GamePlace(placeName, gameName);
            return View(gamePlace);
            //return RedirectToAction(placeName + "__game" + gameName);// 
        }

        public ActionResult Index(string name)
        {
            name = name.Replace("__game_", "|");
            var nameParts = name.Split('|');
            string placeName = nameParts[0];
            string gameName = nameParts[1];

            return RedirectToAction("Go", new { placeName = placeName, gameName = gameName });
        }


        public ActionResult ViewSource(string name)
        {
            var game = new GamePlace(name);
            return View(game);
        }

        public ActionResult ListRevisions(string name)
        {
            return RedirectToAction("List", "History", new { name = name, innerType = "GamePlace" });
        }

        //
        // GET: /Game/Edit/5
        public ActionResult Edit(string name)
        {
            var gamePlace = new GamePlace(name);

            return View(gamePlace);
        }

        //
        // POST: /Game/Edit/5
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(string name, FormCollection collection)
        {
            var gamePlace = new GamePlace(name);

            try
            {
                string reason = collection["Reason"]; 
                gamePlace.DescriptionMarkdown = collection["DescriptionMarkdown"];
                gamePlace.InitPlaceJS = collection["InitPlaceJS"];
                gamePlace.PlaceItemsJson = collection["PlaceItemsJson"];
                gamePlace.PlaceStyle = collection["PlaceStyle"];
                
                gamePlace.Save(reason, User.Identity.Name);
                
                return RedirectToAction("Index", new { name = name } );
            }
            catch
            {
                return View(gamePlace);
            }
        }

        public ActionResult ViewRevision(string name, DateTime revisedAt)
        {
            string revertedBy = User.Identity.Name;
            var gamePlace = GamePlace.LoadRevision(name, revisedAt);
            return View(gamePlace);
        }
    }
}
